#MP Moralization and Foreign Policy Attitudes Replication File: Cleaning and Coding the Data for Study 2
####Last updated: 10 June 2025

###Analyses carried out using R version 4.4.3 in RStudio version Version XXX on Lenovo ThinkPad X1 Carbon Gen 12 Intel Core Ultra 7 155U, 1700 Mhz, 12 running Windows 11 Enterprize

#This file loads packages, functions, and prepares the data for analysis - complete this file before running MP_study2_1.R for complete replication!

#Uncomment below to install packages as needed
#install.packages("ggplot2")
#install.packages("xtable")
#install.packages("psych")
#install.packages("stargazer")
#install.packages("plyr")
#install.packages("ggstance")
#install.packages("gridExtra")
#install.packages("MASS")
#install.packages("interflex")


#Load Packages
library(foreign)
library(ggplot2)
library(xtable)
library(psych)
library(stargazer)
library(plyr)
library(ggstance)
library(gridExtra)
library(MASS)
library(interflex)


#Load the data
setwd() #Set your working directory to the folder containing the data
data <- read.csv("MP_study2_data.csv")


# ### Prune the data per pre-registered criteria --------------------------

nrow(data)#3226

#Survey did not proceed for those who did not consent:
x <- which(data$consent==1)
data <- data[x,] #3226

#Drop respondents who report under 18 on first page of survey:
table(data$age)
x <- which(data$age==99) ##"under 18" category coded as 99
data <- data[-x,] #3223

#Retain only US participants:
table(data$country, useNA = "ifany")
x <- which(data$country=="notus")
data <- data[-x,] #3221

#Drop responses flagged as bots by recaptcha (<0.5)
table(data$Q_RecaptchaScore, useNA="ifany")
x <- which(data$Q_RecaptchaScore<0.5)
data <- data[-x,] #3212

#Drop responses flagged as bots by relevantID fraud score (>= 30)
table(data$Q_RelevantIDFraudScore, useNA="ifany")
x <- which(data$Q_RelevantIDFraudScore>=30)
data <- data[-x,] #3131

#Drop responses flagged as duplicates (>= 75)
table(data$Q_RelevantIDDuplicateScore, useNA="ifany")
x <- which(data$Q_RelevantIDDuplicateScore>=75)
data <- data[-x,] #3104


### "Respondents who fail the first pre-treatment attention check will be excluded from analysis"
round(prop.table(table(data$screener1))*100, digits=2) # 97.78 correctly selected options 1 and 2 on the screener
data$screenercorrect <- ifelse(data$screener1=="1,2", 1, 0) 

#drop respondents who failed screener
x <- which(data$screenercorrect==0)
data <- data[-x,] #3035



# ###Variable Coding Functions -----------------------------------------------


#Function to rescale variables to range from 0 to 1
rescale <- function(x){
  return((x-min(x,na.rm=TRUE))/(max(x-min(x,na.rm=TRUE),na.rm=TRUE)))
}

#Function to recode variables
recode <- function(variable, reverse=FALSE, maxVal, minVal, binarize=FALSE, x=NA, x2){
  if (is.factor(variable)){variable <- as.numeric(variable)}
  if (missing(maxVal)){maxVal <- max(variable, na.rm=TRUE)}
  if (missing(minVal)){minVal <- min(variable, na.rm=TRUE)}
  variable[variable > maxVal] <- NA
  variable[variable < minVal] <- NA
  if (reverse){
    temp <- variable
    for (j in 1:maxVal){
      temp[which(variable==j)] <- maxVal-j+1
    }
    return(temp)
  }
  if (binarize){
    if (is.na(x)){stop("Specify the value to dichotomize on")}
    temp <- variable
    if (missing(x2)){
      i <- which(variable == x)
      k <- which(variable < x | variable > x)
    }
    else{
      i <- which(variable >= x & variable <= x2)
      k <- which(variable < x | variable > x2)
    }
    temp[i] <- 1
    temp[k] <- 0
    return(temp)
  }
  return(variable)
}

#Function to summarise means 
summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
  library(plyr)
  
  # New version of length which can handle NA's: if na.rm==T, don't count them
  length2 <- function (x, na.rm=FALSE) {
    if (na.rm) sum(!is.na(x))
    else       length(x)
  }
  
  # This does the summary. For each group's data frame, return a vector with
  # N, mean, and sd
  datac <- ddply(data, groupvars, .drop=.drop,
                 .fun = function(xx, col) {
                   c(N    = length2(xx[[col]], na.rm=na.rm),
                     mean = mean   (xx[[col]], na.rm=na.rm),
                     sd   = sd     (xx[[col]], na.rm=na.rm)
                   )
                 },
                 measurevar
  )
  
  # Rename the "mean" column    
  datac <- rename(datac, c("mean" = measurevar))
  
  datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean
  
  # Confidence interval multiplier for standard error
  # Calculate t-statistic for confidence interval: 
  # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
  ciMult <- qt(conf.interval/2 + .5, datac$N-1)
  datac$ci <- datac$se * ciMult
  
  return(datac)
}


# Variable Coding: Demographics and political attitudes ---------------------------------------------------------

#Gender
data$man <- recode(data$gender, binarize =TRUE, x="1") #1 if man, 0 if else

#Age
data$age1 <- recode(data$age, binarize=TRUE, x=1, x2=2) #18-34
data$age2 <- recode(data$age, binarize=TRUE, x=3) #35-44
data$age3 <- recode(data$age, binarize=TRUE, x=4, x2=5) #45-64
data$age4 <- recode(data$age, binarize=TRUE, x=6, x2=8) #65 + 


##Party 
data$rep <- recode(data$pid3, binarize=TRUE, x=1) #Republican
data$dem <- recode(data$pid3, binarize=TRUE, x=2) #Democrat
data$ind <- recode(data$pid3, binarize=TRUE, x=3, x2=4) #Independent or something else


data$pid7 <- ifelse(data$rep==1 & data$pidrep==1, 7,
                    ifelse(data$rep==1 & data$pidrep==2, 6,
                           ifelse(data$ind==1 & data$pidlean==2, 5,
                                  ifelse(data$ind==1 & data$pidlean==3, 4,
                                         ifelse(data$ind==1 & data$pidlean==1, 3,
                                                ifelse(data$dem==1 & data$piddem==2, 2,
                                                       ifelse(data$dem==1 & data$piddem==1, 1, NA)))))))
data$pid71 <- rescale(data$pid7) #7 point party scale, higher values = strong republican

#Party IDs with leaners
data$pidreplean <- ifelse(data$pid7 > 4, 1,
                          ifelse(data$pid7 < 5, 0, NA))
data$piddemlean <- ifelse(data$pid7 < 4, 1,
                          ifelse(data$pid7  >3 , 0, NA))
data$pidtrueind <- ifelse(data$pid7 == 4, 1,
                          ifelse(data$pid7>4 | data$pid7<4 , 0, NA))

#Ideology
data$ideo1 <- rescale(data$ideo) #higher values = extremely liberal


#MI/CI
data$mi1 <- rescale(data$mi) #higher values = strongly agree strike at opponent
data$ci1 <- rescale(data$ci) #higher values = strongly agree build consensus

#Political Interest
data$polint1 <- rescale(data$polint) #higher values = extremely interested


###DEMOGRAPHICS BLOCK 2 (this block appears after experiment 1 in the survey flow)

#Race
data$white <- recode(data$race, binarize = TRUE, x=3)
data$black <- recode(data$race, binarize = TRUE, x=1)

#Latino ethnicity
data$latinoy <- recode(data$latino, binarize=TRUE, x=2) #dummy indicating that respondent is of latino origin

#Non-hispanic white
data$nhwhite <- ifelse(data$white==1 & data$latinoy==0, 1,
                       ifelse(is.na(data$white) | is.na(data$latinoy), NA, 0))

#Education
data$university <- recode(data$educ, binarize=TRUE, x=5, x2=6) #university education

####Screener 2:
data$screener2correct <- recode(data$screener2, binarize=TRUE, x=4) #Correctly responds that the statement "The letter C comes after the letter D" is "not at all accurate"


# Variable coding: Pre-treatment moral conviction and policy support ------------------------------------------

data$pre_health1 <- rescale(data$pre_health) #pre-treatment support vaccine aid
data$pmc_health1 <- rescale((data$core_health + data$fund_health)) #pre-treatment moral conviction about vaccine aid

data$pre_counter1 <- rescale(data$pre_counter) #pre-treatment support pressuring other countries on counter-terrorism
data$pmc_counter1 <- rescale((data$core_counter + data$fund_counter)) #pre-treatment moral conviction about pressuring other countries on counter-terrorism

data$pre_ldcs1 <- rescale(data$pre_ldcs) #pre-treatment support digital access aid
data$pmc_ldcs1 <- rescale((data$core_ldcs + data$fund_ldcs)) #pre-treatment moral conviction about digital access aid

data$pre_nuke1 <- rescale(data$pre_nuke) #pre-treatment support U.S. pressure against maraging steel
data$pmc_nuke1 <- rescale((data$core_nuke + data$fund_nuke)) #pre-treatment moral conviction about U.S. pressure against maraging steel

data$pre_un1 <- rescale(data$pre_un) #pre-treatment support for cooperating through institutions
data$pmc_un1 <- rescale((data$core_un + data$fund_un)) #pre-treatment moral conviction about cooperating through institutions

data$pre_climate1 <- rescale(data$pre_climate) #pre-treatment support cooperation for climate change
data$pmc_climate1 <- rescale((data$core_climate + data$fund_climate)) #pre-treatment moral conviction about cooperation for climate change

data$pre_sanc1 <- rescale(data$pre_sanc) #pre-treatment support lifting tariffs
data$pmc_sanc1 <- rescale((data$core_sanc + data$fund_sanc)) #pre-treatment moral conviction about lifting tariffs

data$pre_hr1 <- rescale(data$pre_hr) # pre-treatment support promoting human rights
data$pmc_hr1 <- rescale((data$core_hr + data$fund_hr)) #pre-treatment moral conviction about promoting human rights



# Variable Coding: Treatment Assignment ----------------------------------------------------

## Create treatment dummies

#Vaccine vignette:
data$vaxtreat <- ifelse(data$FL_11_DO=="vaccine_hc" | data$FL_76_DO=="vaccine_hc", "highaid",  #FL_11_DO is the randomizer for aid first group, 76_DO for security first group
                        ifelse(data$FL_11_DO=="vaccine_lc" | data$FL_76_DO=="vaccine_lc", "lowaid", NA))

data$vaxtreat <- factor(data$vaxtreat)
data$vaxtreat <- relevel(data$vaxtreat, ref="lowaid")

#Counter-terrorism vignette:
data$terrtreat <- ifelse(data$FL_20_DO=="terror_hc" | data$FL_97_DO=="terror_hc", "highterr",  #FL_20_DO is the randomizer for aid first group, 97_DO for security first group
                         ifelse(data$FL_20_DO=="terror_lc" | data$FL_97_DO=="terror_lc", "lowterr", NA))

data$terrtreat <- factor(data$terrtreat)
data$terrtreat <- relevel(data$terrtreat, ref="lowterr")

#Viewing order 
data$aidfirst <- ifelse(data$FL_73_DO=="FL_72", "aidfirst",
                        ifelse(data$FL_73_DO=="FL_74", "terrfirst", NA)) #FL_73_DO is the aid/security order randomizer in the survey flow; FL_72 is the aid first group, FL_74 is the security first group

data$aidfirst <- factor(data$aidfirst)
data$aidfirst <- relevel(data$aidfirst, ref="terrfirst")

# Post-treatment Variables: Primary outcomes -----------------------------------------------------

#Vaccine vignette
#Policy Support:
data$support_vaccine <- ifelse(data$vaxtreat=="lowaid", data$support_vaccinelc, 
                               ifelse(data$vaxtreat=="highaid", data$support_vaccinehc, NA)) #combine the two treatment groups
data$suppvax1 <- rescale(data$support_vaccine) # higher values = "strongly support"

#Moral Conviction
data$fund_vax <- ifelse(data$vaxtreat=="lowaid", data$fund_vaccinelc, 
                        ifelse(data$vaxtreat=="highaid", data$fund_vaccinehc, NA))#combine the two treatment groups

data$fund_vax1 <- rescale(data$fund_vax) # higher values = "very much" 
data$care_vax1 <- rescale(data$care_e1) #higher values = "a great deal"

#Actions:
data$petition_vax <- recode(data$petition_e1, binarize=TRUE, x=1, x2=2) #Yes sign a petition
data$contact_vax <- recode(data$contact_e1, binarize=TRUE, x=1, x2=2) #Yes contact pol
data$socialmedia_vax <- recode(data$socialmedia_e1, binarize=TRUE, x=1, x2=2) #Yes post on socials

data$actions_vax <- (data$petition_vax + data$contact_vax + data$socialmedia_vax) #actions index

#Counter-terrorism vignette
#Policy support:
data$support_terror <- ifelse(data$terrtreat=="lowterr", data$support_terrorlc, 
                              ifelse(data$terrtreat=="highterr", data$support_terrorhc, NA)) #combine the two treatment groups

data$suppterr1 <- rescale(data$support_terror) # higher values = "strongly support"

#Moral Conviction: 
data$fund_terror <- ifelse(data$terrtreat=="lowterr", data$fund_terrorlc, 
                           ifelse(data$terrtreat=="highterr", data$fund_terrorhc, NA))#combine the two treatment groups

data$fund_terror1 <- rescale(data$fund_terror) # higher values = "very much" 
data$care_terr1 <- rescale(data$care_e2) #higher values = "a great deal"

#Actions:
data$petition_terr <- recode(data$petition_e2, binarize=TRUE, x=1, x2=2) #Yes sign a petition
data$contact_terr <- recode(data$contact_e2, binarize=TRUE, x=1, x2=2) #Yes contact pol
data$socialmedia_terr <- recode(data$socialmedia_e2, binarize=TRUE, x=1, x2=2) #Yes post on socials

data$actions_terr <- (data$petition_terr + data$contact_terr + data$socialmedia_terr) #actions index


# Post-treatment Variables: Additional questions------------------------------------------

#Vaccine vignette:
data$vax_eff1 <- rescale(data$consequences_e1) #definitely will be effective
data$vax_pres1 <- rescale(data$president_e1) #definitely will approve of president

data$vax_impright1 <- rescale(data$importance_e1_1) #very important morally right or wrong
data$vax_impexp1 <- rescale(data$importance_e1_2) #very important cost
data$vax_impeff1 <- rescale(data$importance_e1_3) #very important effective
data$vax_impbipart1 <- rescale(data$importance_e1_4) #very important bipartisan

#Counter-terrorism vignette:
data$terr_eff1 <- rescale(data$safer_e2) #definitely will be safer
data$terr_pres1 <- rescale(data$president_e2) #definitely will approve of president

data$terr_impright1 <- rescale(data$importance_e2_1) #very important morally right or wrong
data$terr_impexp1 <- rescale(data$importance_e2_2) #very important cost
data$terr_impeff1 <- rescale(data$importance_e2_3) #very important effective
data$terr_impbipart1 <- rescale(data$importance_e2_4) #very important bipartisan


# Create data subsets for subgroup analyses: ----------------------------------------------------

dat.vsupp <- subset(data, data$pre_health1>=0.75) #Somewhat or strongly support
dat.vopp <- subset(data, data$pre_health1<0.75) #strongly oppose, somewhat oppose, neither support nor oppose

dat.tsupp <- subset(data, data$pre_counter1>=0.75) #Somewhat or strongly support
dat.topp <- subset(data, data$pre_counter1<0.75) #strongly oppose, somewhat oppose, neither support nor oppose


d.aidfirst <- subset(data, data$aidfirst=="aidfirst")
d.terrfirst <- subset(data, data$aidfirst=="terrfirst")

d.aidfirst.vsup <- subset(d.aidfirst, d.aidfirst$pre_health1>=0.75) #Somewhat or strongly support
d.aidfirst.vopp <- subset(d.aidfirst, d.aidfirst$pre_health1<0.75) #strongly oppose, somewhat oppose, neither support nor oppose

dat.terrfirst.tsupp <- subset(d.terrfirst, d.terrfirst$pre_counter1>=0.75) #Somewhat or strongly support
dat.terrfirst.topp <- subset(d.terrfirst, d.terrfirst$pre_counter1<0.75) #strongly oppose, somewhat oppose, neither support nor oppose


# #Save the data ----------------------------------------------------------

write.csv(data, "MP_study2_coded.csv") 



